package com.it.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.io.IOException;
import java.util.List;

/**
 * JS数值超过15位精度就会丢失 需要转成字符串
 * @author lankc
 * @date 2019-04-29
 */
@Configuration
public class JsBigNumberInterconversionConfiguration extends WebMvcConfigurerAdapter {

    public final static BigNumberSerializer instance = new BigNumberSerializer();

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        for (HttpMessageConverter converter : converters) {
            if (converter instanceof MappingJackson2HttpMessageConverter) {
                ObjectMapper objectMapper = ((MappingJackson2HttpMessageConverter)converter).getObjectMapper();
                SimpleModule simpleModule = new SimpleModule();
                simpleModule.addSerializer(Long.class, instance);
                simpleModule.addSerializer(Long.TYPE, instance);
                objectMapper.registerModule(simpleModule);
            }
        }
    }

    private static class BigNumberSerializer extends ToStringSerializer {

        private final static long MAX_NUMBER = 999999999999999L;

        @Override
        public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException {
            if (value instanceof Long && (Long) value > MAX_NUMBER) {
                super.serialize(value, gen, provider);
            } else {
                gen.writeNumber(((Long) value).longValue());
            }
        }
    }
}
